﻿namespace Home.Mvc
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Web;
    using System.Web.Mvc;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class ProductUploadHandleErrorAttribute : HandleErrorAttribute
    {
        public string RunningHtmlId { get; set; }
        public string SuccessHtmlId { get; set; }
        public string FailureHtmlId { get; set; }

        public override void OnException(ExceptionContext filterContext)
        {
            Debug.Assert(filterContext != null);

            MvcHandleErrorHelper.Handle(filterContext);

            if (filterContext.ExceptionHandled)
            {
                return;
            }

            var exception = filterContext.Exception;

            if (!this.ExceptionType.IsInstanceOfType(exception))
            {
                return;
            }

            var statusCode = new HttpException(null, exception).GetHttpCode();
            if (statusCode != 500)
            {
                return;
            }

            var html = ProductUploadHelper.BuildResponseHtml(false, this.RunningHtmlId, this.SuccessHtmlId, this.FailureHtmlId);

            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 200;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
            filterContext.HttpContext.Response.ContentEncoding = Encoding.UTF8;
            filterContext.HttpContext.Response.ContentType = "text/html";
            filterContext.HttpContext.Response.Write(html);
        }
    }
}